package com.palmwindActivity.app.main;


import java.util.Vector;
import java.util.concurrent.ThreadPoolExecutor;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.google.protobuf.InvalidProtocolBufferException;
import com.palmwindActivity.app.AbstractServiceProxy;
import com.palmwindActivity.app.ICommConstants;
import com.palmwindActivity.app.IServiceProxyConstants;
import com.palmwindActivity.app.IServiceProxyListener;
import com.palmwindActivity.app.RequestParam;
import com.palmwindActivity.proto.PictureProto;
import com.palmwindActivity.proto.ProtoBuf;


public class ImageServiceProxy extends AbstractServiceProxy implements IImageServiceProxy{
	
	protected Vector<Bitmap> imagesVector;
	
	public ImageServiceProxy(ThreadPoolExecutor threadpool, IServiceProxyListener listener)
	{
		super(threadpool, listener);
		imagesVector = new Vector<Bitmap>();
	}
	
	public void requestImage(long timeStamp) {
		RequestParam param = new RequestParam(IServiceProxyConstants.ACTION_GET_PICTURE, this);
		param.params = new Vector();
		param.params.add(Long.valueOf(timeStamp));
		Vector requestVector= this.createProtoBufReq(param);
		if(requestVector != null && requestVector.size() > 0)
		{
			sendData(requestVector, IServiceProxyConstants.ACTION_GET_PICTURE, 15000, 0);
		}
		
	}

	public Vector<Bitmap> getImages()
	{
		return imagesVector;
	}
	protected void addRequestArgs(Vector<ProtoBuf> request, RequestParam requestItem) {
		
		int size = requestItem.params.size();
		if(size == 1)
		{
			com.palmwindActivity.proto.PictureProto.PicturesReq.Builder builder = PictureProto.PicturesReq.newBuilder();
			builder.setTimeStamp(System.currentTimeMillis());
			builder.setReqAction(IServiceProxyConstants.ACTION_GET_PICTURE);
			PictureProto.PicturesReq req = builder.build();
			ProtoBuf pb = new ProtoBuf();
            pb.setBufferData(req.toByteArray());
            pb.setObjType(IServiceProxyConstants.ACTION_GET_PICTURE);
            
            request.add(pb);
		}
		
	}

	protected void handleResponse(ProtoBuf[] response) {
		
		if (response != null) {
			try {
				for (int index = 0; index < response.length; index++) {

					PictureProto.PicturesResp resp = PictureProto.PicturesResp
							.parseFrom(response[index].getBufferData());
					int size = resp.getPicturesCount();
					for (int i = 0; i < size; i++) {
						PictureProto.PicturesResp.Picture picture = resp
								.getPictures(i);
						Bitmap bitmap = BitmapFactory.decodeByteArray(picture
								.getImagedata().toByteArray(), 0, picture
								.getImagedata().size());
						imagesVector.add(bitmap);
					}
				}
			} catch (InvalidProtocolBufferException e) {
				// TODO Auto-generated catch block
				this.status = ICommConstants.NETWORK_PARSER_ERROR;
			}
		}
		this.status = ICommConstants.NETWORK_FAIL;
	}
	
	
}
